<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<body>
<div id="messages" style="height: 100%;overflow: auto;white-space:pre-line"></div>
<div id="switch"
     style="position: fixed;bottom: 0;right: 0;display: flex;align-items: end;justify-content: end;font-size: 12px;">
    <button class="layui-btn" id="autoScroll">自动滚动</button>
    <div style="margin-left: 5px;">自动滚动间隔:<input type="number" id="timeout" value="1000">毫秒</div>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    window.getUrlParams = function (key) {
        //获取url参数
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
        var url = decodeURI(window.location.search)
        var r = url.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
    var transID = getUrlParams('transID');
    //alert(transID);
    var socket;
    var loglength = 0;
    var autoScroll = true;
    var timeout = 1000;
    var pre_statue = 2;
    openSocket();

    function openSocket() {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            //后续将这一块改为通过transID来获取日志
            var socketUrl = `http://${location.host}/imserver/${transID}`;
            socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
            console.log(socketUrl);
            if (socket != null) {
                socket.close();
                socket = null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function () {
                console.log("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());

            };
            //获得消息事件
            socket.onmessage = function (msg) {
                const json = JSON.parse(msg.data);
                var date = formateNow();
                var ele = document.getElementById('messages');
                if (json.msgType == 'log') {
                    pre_statue = json.prestatue;
                    try {
                        var logs = JSON.parse(json.data);

                        if (logs.log != null) {
                            if (logs.log.length >= Number.MAX_VALUE) {
                                ele.innerHTML
                                    += `<br/><br/>******************${date}******************<br/><br/>日志已超过最大读取。请下载查看。`;
                                return;
                            }
                            if (logs.logLength != logs.log.length) {
                                var __log = logs.log.substr(logs.logLength);
                                loglength = logs.log.length;
                                ele.innerHTML
                                    += `<br/><br/>******************${date}******************<br/><br/>${__log}`;
                            }
                        } else {
                            loglength = -1;
                            ele.innerHTML
                                += `<br/><br/>******************${date}******************<br/><br/>${json.data}`;
                        }
                    } catch {
                        loglength = -1;
                        ele.innerHTML
                            += `<br/><br/>******************${date}******************<br/><br/>${json.data}`;
                    }
                    if (autoScroll) {
                        if (ele.innerHTML.length >= Number.MAX_VALUE) {
                            ele.innerHTML = '';
                        }
                        ele.scrollIntoView({
                            block: 'end',
                            inline: 'end',
                            behavior: "smooth"
                        })
                    }
                }

                if (json.msgType == 'init') {
                    ele.innerHTML
                        += `<br/><br/>******************${date}******************<br/><br/>${json.data}`;
                }
                if (autoScroll) {
                    setTimeout(getLog, timeout);
                }
                //发现消息进入    开始处理前端触发逻辑
            };

            //关闭事件
            socket.onclose = function () {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function () {
                console.log("websocket发生了错误");
            }
        }
    }

    function formateNow() {
        var date = new Date();
        var hours = `${date.getHours()}`
        if (date.getHours() <= 9) {
            hours = `0${date.getHours()}`
        }

        var minutes = `${date.getMinutes()}`
        if (date.getMinutes() <= 9) {
            minutes = `0${date.getMinutes()}`
        }

        var seconds = `${date.getSeconds()}`
        if (date.getSeconds() <= 9) {
            seconds = `0${date.getSeconds()}`
        }
        return `${hours}:${minutes}:${seconds}`;
    }

    function sendMessage() {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            //console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
            //socket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
        }
    }

    function getLog() {
        socket.send(JSON.stringify({
            logLength: loglength,
            transID: transID,
            prestatue: pre_statue
        }))
    }

    document.getElementById("autoScroll").onclick = () => {
        if (autoScroll) {
            autoScroll = false;
            document.getElementById("autoScroll").innerText = "停止自动滚动";
        } else {
            autoScroll = true;
            document.getElementById("autoScroll").innerText = "自动滚动";
            getLog();
        }
    }

    document.getElementById("timeout").onchange = () => {
        timeout = document.getElementById("timeout").value;
    }
</script>

</html>
